from datetime import datetime

from rest_framework import serializers
from .models import SegmentSchedule
from ship_segments.models import ShipSegment


class ShipSegmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShipSegment
        fields = ['ship_number', 'ship_type', 'segment_number']  # 根据需要调整字段


class SegmentScheduleSerializer(serializers.Serializer):  # 注意这里使用的是 Serializer 而不是 ModelSerializer
    segment_schedule_id = serializers.IntegerField()
    ship_segments_id = serializers.IntegerField()
    mid_schedule_start = serializers.DateTimeField(allow_null=True)
    mid_schedule_end = serializers.DateTimeField(allow_null=True)
    earliest_start = serializers.DateTimeField(allow_null=True)
    latest_start = serializers.DateTimeField(allow_null=True)
    latest_end = serializers.DateTimeField(allow_null=True)
    ship_segment_details = ShipSegmentSerializer()  # 嵌套的 ShipSegment 数据


class SegmentScheduleUpdateInputSerializer(serializers.Serializer):
    segment_schedule_id = serializers.IntegerField()
    mid_schedule_start = serializers.DateTimeField(allow_null=True, required=False)
    mid_schedule_end = serializers.DateTimeField(allow_null=True, required=False)
    earliest_start = serializers.DateTimeField(allow_null=True, required=False)
    latest_start = serializers.DateTimeField(allow_null=True, required=False)
    latest_end = serializers.DateTimeField(allow_null=True, required=False)

    # 保留这些字段，虽然不处理
    ship_segments_id = serializers.IntegerField(required=False)
    segment_number = serializers.CharField(required=False)

    def update(self, instance, validated_data):
        for field in validated_data:
            setattr(instance, field, validated_data[field])
        instance.save()
        return instance


class SegmentScheduleCreateSerializer(serializers.Serializer):
    ship_segments_id = serializers.IntegerField(required=True)
    segment_number = serializers.CharField(max_length=50, required=True)
    mid_schedule_start = serializers.DateTimeField(allow_null=True, required=False)
    mid_schedule_end = serializers.DateTimeField(allow_null=True, required=False)
    earliest_start = serializers.DateTimeField(allow_null=True, required=False)
    latest_start = serializers.DateTimeField(allow_null=True, required=False)
    latest_end = serializers.DateTimeField(allow_null=True, required=False)

    def create(self, validated_data):
        return SegmentSchedule.objects.create(**validated_data)

# 自定义时间字段支持灵活格式
class FlexibleDateTimeField(serializers.Field):
    def to_internal_value(self, data):
        if not data:
            return None
        try:
            if isinstance(data, str):
                # 支持格式：'2025-06-07 10:00:00'
                return datetime.strptime(data.strip(), '%Y-%m-%d %H:%M:%S')
            elif isinstance(data, datetime):
                return data
            else:
                raise serializers.ValidationError("日期格式错误")
        except ValueError:
            raise serializers.ValidationError("无法解析日期时间")

    def to_representation(self, value):
        return value.strftime('%Y-%m-%d %H:%M:%S') if value else None


# 导入用的序列化器
class SegmentScheduleImportSerializer(serializers.Serializer):
    ship_number = serializers.CharField(max_length=50, required=True)
    segment_number = serializers.CharField(max_length=50, required=True)

    mid_schedule_start = FlexibleDateTimeField(required=False)
    mid_schedule_end = FlexibleDateTimeField(required=False)
    earliest_start = FlexibleDateTimeField(required=False)
    latest_start = FlexibleDateTimeField(required=False)
    latest_end = FlexibleDateTimeField(required=False)

    def validate(self, data):
        ship_number = data.get('ship_number')
        segment_number = data.get('segment_number')

        try:
            ship_segment = ShipSegment.objects.get(
                ship_number=ship_number,
                segment_number=segment_number
            )
            data['ship_segments_id'] = ship_segment.ship_segments_id
        except ShipSegment.DoesNotExist:
            raise serializers.ValidationError({
                "ship_number": ship_number,
                "segment_number": segment_number,
                "error": "未找到匹配的船舶分段信息"
            })

        return data

    def create(self, validated_data):
        print("[DEBUG] Validated data:", validated_data)

        ship_segments_id = validated_data.get('ship_segments_id')

        # 使用 update_or_create 避免重复插入
        schedule, created = SegmentSchedule.objects.update_or_create(
            ship_segments_id=ship_segments_id,
            defaults={
                'segment_number': validated_data.get('segment_number'),
                'mid_schedule_start': validated_data.get('mid_schedule_start'),
                'mid_schedule_end': validated_data.get('mid_schedule_end'),
                'earliest_start': validated_data.get('earliest_start'),
                'latest_start': validated_data.get('latest_start'),
                'latest_end': validated_data.get('latest_end'),
            }
        )

        return schedule

    def update(self, instance, validated_data):
        raise NotImplementedError("不支持直接更新操作")